/*
 * @Author: your name
 * @Date: 2021-06-15 09:28:12
 * @LastEditTime: 2021-07-30 10:18:28
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \base-framework-web\src\net\common\API.ts
 */
/**
 * request 网络请求工具
 * 更详细的 api 文档: https://github.com/umijs/umi-request
 */
import { message } from 'antd';
import { extend } from 'umi-request';
import Const from '@/utils/Const';

class RequestApi {
  request;
  url: string = '';
  constructor() {
    this.request = extend({
      // prefix: '/api',
      timeout: 0,
      credentials: 'include', // 默认请求是否带上cookie
      errorHandler: this.errorHandler,
    });
    // request拦截器
    this.request.interceptors.request.use((url, options) => {
      // console.log(options, '--options--');
      const authorization = localStorage.getItem('authorization') || '';
      let getHead = { Authorization: 'Bearer ' + authorization };
      if (url.indexOf('/oauth/token') > -1) {
        getHead = options.header;
      }
      return {
        options: {
          ...options,
          interceptors: true,
          headers: getHead,
        },
      };
    });
    // request响应器
    // this.request.interceptors.response.use(async (response, options) => {
    //   console.log(response, '--response--');
    //   const data = await response.clone().json();
    //   console.log(data, '--data--');
    //   return this.responseHandler(response);
    // })
  }

  // 错误处理
  errorHandler(err: any) {
    console.error(err, '--err--');
  }

  // res处理
  responseHandler(response: any) {
    console.log(response, '--response--');
    // if (response && response.code) {
    if (response) {
      if (Const.successCode !== response.code && !response.access_token) {
        message.warning(response.message || '');
      }
      return response;
    } else {
      return {
        code: '-1',
        msg: '系统错误',
      };
    }
  }

  getRequest(apiObj: any) {
    // 接口请求地址
    const url: string = apiObj.url || '';
    // 操作日志埋点处理
    if (apiObj.isQuery) {
      this.url = apiObj.otherUrl || '';
      delete apiObj.isQuery;
      delete apiObj.otherUrl;
    } else {
      this.url = url;
    }
    delete apiObj.url;
    // 请求头处理
    apiObj.header = {
      ...apiObj.header,
      // ...Const.getLogParams(this.url || ''), // 操作日志埋点请求参数
    };

    return this.request(url, {
      ...apiObj,
    }).then((res) => this.responseHandler(res));
  }
}

export { RequestApi };
